package com.enbatis.mybatisplugs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.enbatis.mybatisplugs.base.BaseController;
import com.enbatis.mybatisplugs.base.IRedisService;
import com.enbatis.mybatisplugs.commons.sql.Wrapper;
import com.enbatis.mybatisplugs.commons.utils.ResultReturn;
import com.enbatis.mybatisplugs.entity.TCategory;
import com.enbatis.mybatisplugs.plugin.Pages;
import com.enbatis.mybatisplugs.toolkit.HttpRequestUtils;
import com.github.pagehelper.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.enbatis.mybatisplugs.entity.NewsData;
import com.enbatis.mybatisplugs.service.NewsDataService;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("v1/news_data")
public class NewsDataController extends BaseController {

@Autowired
private NewsDataService newsDataService;

    @Autowired
    private IRedisService redisService;


    @PostMapping("/add")
    public ResultReturn<NewsData> add(@RequestBody NewsData newsData){
        return  success(newsDataService.insert(newsData));
    }


    @DeleteMapping("/delete")
    public ResultReturn<Integer> delete(@RequestParam("id") Long id){
        return success(newsDataService.deleteById(id));
    }


    @PutMapping("/{id}")
    public  ResultReturn<Integer> update(@PathVariable("id") Long id,@RequestBody NewsData newsData){
        newsData.setId(id);
        return success(newsDataService.updateById(newsData));
    }


    @GetMapping("/{id}")
    public ResultReturn<NewsData> get(@PathVariable("id") Long id) {
        return success(newsDataService.getById(id));
    }


    @GetMapping("/list")
    public ResultReturn<List<NewsData>> getList(NewsData newsData){
        return success(newsDataService.list(new Wrapper<>(newsData)));
    }


    @ApiOperation(value = "分页列表", notes = "分页查询数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "请求数据的页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "rows", value = "每页条数", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "sidx", value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sord", value = "排序方式", paramType = "query", dataType = "String"),
    })
    @PostMapping("/page")
    public ResultReturn<Pages<NewsData>> getPage(NewsData category){
        Map<String,String> map= new HashMap<>();
        map.put("type","top");
        map.put("key","405da35bb1f1545a6fd8ae51099eb425");
        JSONObject jsonObject=  HttpRequestUtils.httpGet("http://v.juhe.cn/toutiao/index",map);
         if (null==jsonObject){



             return success(newsDataService.page(getPage(),new Wrapper<>(category).orderBy("date",false)));
         }
        JSONObject result=  (JSONObject)jsonObject.get("result");
         if (null==result){
             return success(newsDataService.page(getPage(),new Wrapper<>(category).orderBy("date",false)));
         }
        JSONArray jsonArray=  (JSONArray)result.get("data");
         if (null==jsonArray){
             return success(newsDataService.page(getPage(),new Wrapper<>(category).orderBy("date",false)));
         }
        List<NewsData> newsDataList= jsonArray.toJavaList(NewsData.class);
        if (CollectionUtils.isEmpty(newsDataList)){
            return success(newsDataService.page(getPage(),new Wrapper<>(category).orderBy("date",false)));
        }
        List<NewsData> dataList=newsDataService.list(new Wrapper<>(category).setSqlSelect("uniquekey"));

        Map<String,String> uniquekeyMap=new HashMap<>();
        for (NewsData data:dataList) {
            uniquekeyMap.put(data.getUniquekey(),data.getUniquekey());
        }

        List<NewsData> saveList=new ArrayList<>();

        for (NewsData data:newsDataList) {
           if (uniquekeyMap.get(data.getUniquekey())==null){
               saveList.add(data);
           }
        }
        if (CollectionUtils.isNotEmpty(saveList)){
            newsDataService.saveBatch(saveList);
            redisService.remove("uniquekeynewData");
        }

        return success(newsDataService.page(getPage(),new Wrapper<>(category).orderBy("date",false)));
    }

}
